<?php
/**
 * Created by PhpStorm.
 * User: 73640
 * Date: 2018/10/29
 * Time: 15:53
 */

namespace App\Repositories;


use App\Exceptions\WechatException;
use App\Http\Controllers\Admin\Business\Repository\Combo;
use App\Member;
use App\Models\ComboExchange;
use App\Models\MemberExchange;
use Illuminate\Support\Carbon;

class ExchangeRepository
{
    protected function uuid($prefix=''){
        $str = md5(uniqid(mt_rand(), true));
        $uuid  = substr($str,0,8);
        if(ComboExchange::where('code',$uuid)->first()){
           $this->uuid();
        }
        return $prefix . $uuid;
    }

    /**
     * @param $combo_id
     * @param $num
     */
    public function createdExchange($combo_id,$num){
       $combo= Combo::find($combo_id);
       // 检测套餐是否存在
        if(!$combo){
            throw  new WechatException('套餐不存在');
        }
        $data=[];
        for ($i=0;$i<$num;$i++){
           $data[$i]['combo_id']=$combo_id;
           $data[$i]['code']=$this->uuid();
           $data[$i]['created_at']=Carbon::now();
        }
        \DB::table('combo_exchange')->insert($data);
        return $data;
    }

    /**
     * @param $code
     */
    public function ExchangeToUser(Member $member,$code){
        //检查兑换券是否使用
       $comboExchange= ComboExchange::where('code',$code)->first();

       if($comboExchange){
           throw  new WechatException('激活码已存在');
       }
        $comboExchange=  new ComboExchange();
        $comboExchange->combo_id=2;
        $comboExchange->code=$code;
        $comboExchange->save();

       //写入用户exchange表
       $memberExchange= new MemberExchange();
       $memberExchange->member_id=$member->id;
       $memberExchange->exchange_id=$comboExchange->id;
       $memberExchange->save();
       //改变comboExchange
        $comboExchange->status=1;
        $comboExchange->save();
        //todo 查看套餐是否是电子导游 如果是
        //增加景点次数
        $combo=Combo::find($comboExchange->combo_id);
        Member::where('id',$member->id)->increment('wallet_spots',$combo->times);
        return $combo;
    }




}